package com.example.hospital.api.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.example.hospital.api.common.PageUtils;
import com.example.hospital.api.db.dao.MisUserDao;
import com.example.hospital.api.service.MisUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class MisUserServiceImpl implements MisUserService {

    @Resource
    private MisUserDao misUserDao;

    @Override
    public Integer login(Map param) {
        String username = MapUtil.getStr(param, "username");
        String password = MapUtil.getStr(param, "password");
        MD5 md5 = MD5.create();
        String temp = md5.digestHex(username);
        //前六位字符
        String tempStart = StrUtil.subWithLength(temp, 0, 6);
        //后三位字符
        String tempEnd = StrUtil.subSuf(temp, temp.length() - 3);
        //混淆原始密码并哈希加密
        password = md5.digestHex(tempStart + password + tempEnd);
        param.replace("password", password);
        Integer userId = misUserDao.login(param);
        return userId;
    }

    @Override
    public PageUtils searchByPage(Map param) {
        ArrayList<HashMap> list = null;
        long count = misUserDao.searchCount(param);
        if (count > 0) {
            list = misUserDao.searchByPage(param);
        } else {
            list = new ArrayList<>();
        }
        int page = MapUtil.getInt(param, "page");
        int length = MapUtil.getInt(param, "length");
        PageUtils pageUtils = new PageUtils(list, count, page, length);
        return pageUtils;
    }

    @Override
    @Transactional
    public void insert(Map param) {
//        String username = entity.getName();
//        String password = entity.getPassword();
        String username = MapUtil.getStr(param, "username");
        //调用MapUtil的方法将username提取出来
        String password = MapUtil.getStr(param, "password");
        MD5 md5 = MD5.create();
        String temp = md5.digestHex(username);
        //前六位字符
        String tempStart = StrUtil.subWithLength(temp, 0, 6);
        //后三位字符
        String tempEnd = StrUtil.subSuf(temp, temp.length() - 3);
        //混淆原始密码并哈希加密
        password = md5.digestHex(tempStart + password + tempEnd);
        param.replace("password", password);
        misUserDao.insert(param);
    }

    @Override
    public void deleteByIds(Integer[] ids) {
        misUserDao.deleteByIds(ids);
    }

    @Override
    public HashMap searchById(int id) {
        HashMap map = misUserDao.searchById(id);
        return map;
    }

    @Override
    @Transactional
    public void update(Map param) {
        misUserDao.update(param);
    }
}

